package com.can.controller;

import com.can.domain.ResponseResult;
import com.can.domain.entity.User;
import com.can.domain.vo.PageVO;
import com.can.domain.vo.UserDetailVO;
import com.can.domain.vo.UserInfoVO;
import com.can.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public ResponseResult<PageVO> list(Integer pageNum, Integer pageSize, User user) {
        return userService.page(pageNum, pageSize, user);
    }

    @PostMapping
    public ResponseResult save(@RequestBody @Valid User user) {
        userService.add(user);
        return ResponseResult.okResult();
    }

    @DeleteMapping("/{id}")
    public ResponseResult del(@PathVariable("id") String idString) {
        List<Long> ids = Arrays.stream(idString.split(",")).map(id -> Long.valueOf(id)).collect(Collectors.toList());
        userService.remove(ids);
        return ResponseResult.okResult();
    }

    @GetMapping("/{id}")
    public ResponseResult<UserDetailVO> get(@PathVariable Long id) {
        return ResponseResult.okResult(userService.get(id));
    }

    @PutMapping
    public ResponseResult update(@RequestBody UserInfoVO vo) {
        userService.update(vo);
        return ResponseResult.okResult();
    }

}